/*************************************************************************
 *     >      File Name: configini.c
 *     >    Description: This file is write for parsering configuration file.
 *
 *     >         Author: Yang Xiaohan
 *     >           Mail: yangxiaohan_niki@163.com
 *     >   Created Time: Fri 22 Jul 2022 10:24:28 CST
 *     >   Changed Time: Fri 22 Jul 2022 10:24:28 CST
 **************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "iniparser.h"
#include "configini.h"



int get_config(char *path,user_data *mqtt, int mode)
{
	dictionary			*ini = NULL;
	const char			*brokeraddress;
	int					 brokerport;
	const char			*username;
	const char 			*password;
	const char			*client_id;
	const char			*topic;
	int			 		 QOS;


	//const char			*method;
	//const char			*identifier;
	const char 			*type;
	const char			*state;
	//const char   		*version;
	const char			*clientToken;


	if(!path||!mqtt)
	{
		printf("invalid_argument:%s\n",__FUNCTION__);
		return -1;
	}
	ini = iniparser_load(path);

	if(ini == NULL)
	{
		printf("iniparser_load failure：%s.\n",strerror(errno));
		return -2;
	}

	brokeraddress = iniparser_getstring(ini,"address:host","NULL");
	brokerport = iniparser_getint(ini, "address:port",-1);
	username = iniparser_getstring(ini,"username_pw:username","NULL");
	password = iniparser_getstring(ini,"username_pw:password","NULL");
	client_id =iniparser_getstring(ini,"client_id:client_id","NULL");
	QOS = iniparser_getint(ini, "QOS:QOS",-1);
	//identifier = iniparser_getstring(ini,"json:identifier","NULL");


	if(mode == SUB)
	{
		topic = iniparser_getstring(ini,"sub_topic:topic","NULL");
	}
	else if(mode == PUB)
	{
		topic = iniparser_getstring(ini, "pub_topic:topic","NULL");
		type = iniparser_getstring(ini, "json:type","NULL");
		state = iniparser_getstring(ini,"json:state","NULL");
		clientToken = iniparser_getstring(ini,"json:clientToken","NULL");
	}
	else if(mode != SUB && mode != PUB)
	{
		printf("invalid_argument: %s mode!\n",__FUNCTION__);
		return -3;
	}

	strncpy(mqtt->brokeraddress,brokeraddress,SIZE);
	mqtt->brokerport = brokerport;
	mqtt->QOS = QOS;
	strncpy(mqtt->username,username,SIZE);
	strncpy(mqtt->password,password,SIZE);
	strncpy(mqtt->clientid,client_id,SIZE);
	strncpy(mqtt->topic,topic,SIZE);
	//strncpy(mqtt->identifier,identifier,SIZE);

	if(mode == PUB)
	{
		strncpy(mqtt->type,type,SIZE);
		strncpy(mqtt->state,state,SIZE);
		strncpy(mqtt->clientToken,clientToken,SIZE);
	}
	iniparser_freedict(ini);
	return 0;
	
}



